import { defineConfig, IConfig } from "umi"
import { resolve } from "path"
import ProxyConfig from "./proxy"
import { readdirSync, existsSync } from "fs"

const API_ENV = process.env.API_ENV || "test"
const isDev = process.env.NODE_ENV === "development"
const packagesPath = existsSync(resolve(__dirname, "../../packages"))
  ? resolve(__dirname, "../../packages")
  : existsSync(resolve(__dirname, "../../node_modules/@ruler3d/"))
  ? resolve(__dirname, "../../node_modules/@ruler3d/")
  : existsSync(resolve(__dirname, "../node_modules/@ruler3d/"))
  ? resolve(__dirname, "../node_modules/@ruler3d/")
  : ""
const Key = "ruler3d"

function buildProxy() {
  const proxyList = {} as Record<string, any>
  Object.keys(ProxyConfig).forEach(it => {
    proxyList[`/${it}`] = {
      target: ProxyConfig[it][API_ENV],
      changeOrigin: true,
      pathRewrite: { [`^/${it === "webwalk" ? "" : it}`]: "" }
    }
  })
  return proxyList
}

function getPackageS() {
  const result = {}
  const list = readdirSync(packagesPath)
  list.forEach(m => {
    result[`@${Key}/${m}`] = resolve(packagesPath, `${m}/src/index.ts`)
    result[`@${Key}/${m}/`] = resolve(packagesPath, `${m}/`)
  })
  return result
}

export default defineConfig({
  base: "./",
  outputPath: "../dist/",
  proxy: buildProxy(),
  exportStatic: {
    htmlSuffix: true,
    dynamicRoot: true
  },
  history: {
    type: "browser"
  },
  ignoreMomentLocale: true,
  mountElementId: "app",
  runtimePublicPath: true,
  hash: false,
  chunks: [Key],
  chainWebpack: conf => {
    //替换默认入口名称
    const entryVal = conf.entry("umi").values()
    conf.entryPoints.delete("umi").end().entry(Key).merge(entryVal)
    // if (isDev) {
    conf.module.rules.get("ts-in-node_modules").include.add(packagesPath)
    // }
    //only-fileLoader
    conf.module.rule("no-use-base64").test(/no64/i).use("file-loader").loader("file-loader").options({
      name: "resources/[name].[hash:8].[ext]"
    })
    //imagesLoader
    conf.module
      .rule("images")
      .test(/\.(png|jpe?g|gif|webp|ico)(\?.*)?$/)
      .use("url-loader")
      .loader("url-loader")
      .options({
        limit: 5000,
        name: "resources/[name].[hash:8].[ext]",
        esModule: false,
        fallback: {
          loader: require.resolve("file-loader"),
          options: {
            name: "resources/[name].[hash:8].[ext]",
            esModule: false
          }
        }
      })
    //svgLoader
    conf.module
      .rule("svg")
      .test(/\.(svg)(\?.*)?$/)
      .use("file-loader")
      .loader("file-loader")
      .options({
        name: "resources/[name].[hash:8].[ext]",
        esModule: false
      })
    //fontsLoader
    conf.module
      .rule("fonts")
      .test(/\.(eot|woff|woff2|ttf)(\?.*)?$/)
      .use("file-loader")
      .loader("file-loader")
      .options({
        name: "resources/[name].[hash:8].[ext]",
        esModule: false
      })
    //rawLoader
    conf.module
      .rule("plaintext")
      .test(/\.(txt|text|md)$/)
      .use("raw-loader")
      .loader("raw-loader")
      .options({
        name: "resources/[name].[hash:8].[ext]",
        esModule: false
      })
  },
  define: {
    API_ENV,
    HOST_ENV: JSON.stringify(
      (data => {
        return (e => {
          for (let key in data) {
            e[key] = (item => ({ [API_ENV]: item[API_ENV] }))(data[key])
          }
          return e
        })({})
      })(ProxyConfig)
    )
  },
  dynamicImport: {
    loading: "@/components/utils/PageLoading.tsx"
  },
  locale: {
    antd: false,
    title: true,
    baseNavigator: true,
    baseSeparator: "-"
  },
  dva: false,
  antd: {
    dark: false,
    compact: false
  },
  workerLoader: { inline: "fallback", filename: "worker/[name].js" },
  devServer: {
    https: {
      cert: resolve(__dirname, "./cert/localhost.pem"),
      key: resolve(__dirname, "./cert/localhost-key.pem")
    }
  },
  alias: packagesPath ? getPackageS() : {}
} as IConfig)
